import React from  'react';
import { Form, Card, Button, Input, Icon, Checkbox } from 'antd';
import './ui.scss';

const FormItem = Form.Item;

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this.props.form.validateFields();
  }

  hasErrors = (fieldsError) => {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  }

  handleSubmit(e) {
    e.preventDefault();

    this.props.form.validateFields((error, values) => {
      if (!error) {
        console.log('received values of form:', values);
      }
    });
  }

  render() {
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    const userNameError = isFieldTouched('userName') && getFieldError('userName');
    const passwordError = isFieldTouched('password') && getFieldError('password');
    return (
      <div className="form-test">
        <Card
          title="antd-form-base"
        >
          <Form 
            layout="inline"
            onSubmit={(e) => this.handleSubmit(e)}
          >
            <FormItem
              hasFeedback={userNameError?true:false}
              validateStatus={userNameError ? 'error' : 'success'}
              help={userNameError||''}
            >
              {
                getFieldDecorator("userName", {
                  // initialValue: '',
                  rules: [{
                    required: true,
                    message: '用户名不能为空'
                  }]
                })(
                  <Input id="userName" style={{width:240}} autoComplete="off" type="text" prefix={<Icon type="user"/>} placeholder="用户名"/>
                )
              }
            </FormItem>

            <FormItem
              hasFeedback={passwordError?true:false}
              validateStatus={passwordError ? 'error' : 'success'}
              help={passwordError||''}
            >
              {
                getFieldDecorator('password', {
                  // initialValue: '',
                  rules: [{
                    required: true,
                    message: '密码不能为空'
                  }, {
                    min: 6,
                    max: 12,
                    message: '密码长度在6-12位'
                  }, {
                    pattern: RegExp("^\\w+$", 'g'),
                    message: '密码有数字或者字幕组成'
                  }]
                })(
                  <Input id="password" prefix={<Icon type="lock"/>} style={{width:240}} type="password" placeholder="密码"/>
                )
              }
            </FormItem>

            <FormItem>
              <Button
                type="primary"
                htmlType="submit"
                disabled={this.hasErrors(getFieldsError())}
              >login</Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    );
  }
}

export default Form.create()(LoginForm);